/**
 * Created by luomingzhong on 17/3/19.
 * 这是一个循环列表
 */

class Node {
    constructor(element) {
        this.element = element;
        this.next = null;
    }
}

class LList {
    constructor() {
        this.head = new Node('head');
        this.head.next = this.head;
        this.position = this.head;
        this.count = 1;
    }

    find(item) {
        let currNode = this.head;
        while (currNode.element != item) {
            currNode = currNode.next;
            //当是最后一个节点的时候，返回null
            if (currNode === null) {
                return false;
            }
        }
        return currNode;
    }

    //
    advance(n) {
        let i = 0;
        for (i; i < n; i++) {
            this.position = this.position.next;
        }
    }

    show() {
        return this.position.element;
    }

    insert(newElement, item) {
        let newNode = new Node(newElement);
        let current = this.find(item);
        newNode.next = current.next;
        current.next = newNode;
        this.count += 1;
    }

    //打印链表元素
    display() {
        let currNode = this.head;
        while (!(currNode.next == null)) {
            console.log(currNode.next.element);
            currNode = currNode.next;
        }
    }

    findPrevious(item) {
        let currentNode = this.head;
        while ((currentNode.next.element !== item)) {
            currentNode = currentNode.next;
        }
        return currentNode;
    }

    remove(item) {
        let prevNode = this.findPrevious(item);
        prevNode.next = prevNode.next.next;
        this.count = this.count - 1;
    }

    length() {
        return this.count;
    }
    display(){
        let current = this.head;
        while(current!==this.head){
            current = current.next;
            console.log(current.element);
        }
    }
}

module.exports = LList;